// 登录表单验证和交互增强
document.addEventListener('DOMContentLoaded', function() {
    console.log('login.js: DOMContentLoaded - script loaded');
    const form = document.querySelector('form');
    if (!form) return;

    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        console.log('login.js: submit handler triggered');

        // 收集表单字段（与 register.js 风格一致）
        const fd = new FormData(form);
        const username = (fd.get('username') || '').trim();
        const password = (fd.get('password') || '').trim();

        if (!username) { showErrorMessage('请输入用户名'); return; }
        if (!password) { showErrorMessage('请输入密码'); return; }

        // 生成 request_id
        const now = new Date();
        const request_id = `req-login-${now.getTime()}`;

        // 计算密码哈希（与 register.js 保持一致）
        let password_hash = null;
        try {
            console.log('login.js: computing password hash...');
            password_hash = await hashPassword(password);
            console.log('login.js: computed password_hash=', password_hash);
        } catch (err) {
            console.error('密码哈希失败:', err);
            showErrorMessage('处理密码时出现错误，请重试');
            return;
        }

        // 和 register.js 一样的 payload 结构，但 operation 为 query
        const payload = {
            request_id: request_id,
            operation: 'query',
            database: 'short_video',
            table: 'user',
            condition: { username: username },
            data: { username: username, password_hash: password_hash }
        };

        try {
            console.log('login.js: about to fetch POST to /api/request with payload', payload);
            const resp = await fetch('/api/request', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            console.log('login.js: fetch completed, status=', resp.status);

            let result = null;
            try {
                result = await resp.json();
            } catch (parseErr) {
                console.error('login.js: failed to parse JSON response', parseErr);
            }
            console.log('登录后端返回：', result);

            // 兼容大小写字段名
            const querySuccess = Boolean(result && (result.query_success ?? result.QuerySuccess ?? result.success));
            // 兼容数据为数组或对象
            let dataAny = result && (result.data ?? result.Data);
            let userData = Array.isArray(dataAny) ? (dataAny[0] || null) : dataAny;

            if (querySuccess && userData) {
                const serverHash = userData.password_hash ?? userData.passwordHash ?? null;
                if (serverHash && serverHash === password_hash) {
                    try { localStorage.setItem('username', username); } catch (e) {}
                    // 调用后端接口建立 Django 会话，然后再跳转
                    try {
                        const sresp = await fetch('/accounts/api/session-login', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ username })
                        });
                        const sdata = await sresp.json().catch(() => ({}));
                        if (sresp.ok && sdata && sdata.ok) {
                            showSuccessMessage('登录成功！正在跳转到个人主页...');
                            setTimeout(() => { window.location.href = '/profile/'; }, 600);
                        } else {
                            showErrorMessage('登录会话建立失败，请重试');
                        }
                    } catch (e) {
                        console.error('session-login failed', e);
                        showErrorMessage('网络错误，无法建立登录会话');
                    }
                } else {
                    console.warn('密码哈希不匹配或后端未返回 password_hash', { serverHash, password_hash, userData });
                    showErrorMessage('用户名或密码错误');
                }
            } else {
                // 更准确的错误提示：区分后端不可达与用户不存在
                if (!resp.ok) {
                    showErrorMessage(`登录服务暂不可用（HTTP ${resp.status}）`);
                } else if (result && result.error) {
                    // 来自代理的错误，如 upstream_unreachable / invalid_json 等
                    const emap = {
                        upstream_unreachable: '后端未启动或网络不可达，请先运行 mock_backend.py',
                        upstream_http_404: '后端接口不存在（404）',
                        upstream_http_500: '后端内部错误（500）',
                        invalid_json: '返回数据格式异常',
                    };
                    const tip = emap[result.error] || result.error;
                    showErrorMessage(tip);
                } else {
                    // 正常返回但没有 query_success/data，视为用户不存在
                    const msg = (result && (result.message || result.msg)) || '用户名不存在';
                    showErrorMessage(msg);
                }
            }
        } catch (err) {
            console.error('登录请求失败:', err);
            showErrorMessage('网络错误，请检查连接后重试');
        }
    });

    // 将明文密码做 SHA-256 哈希并返回十六进制字符串（同 register.js）
    async function hashPassword(password) {
        if (!password) return null;
        const enc = new TextEncoder();
        const data = enc.encode(password);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        return bufferToHex(hashBuffer);
    }

    function bufferToHex(buffer) {
        const bytes = new Uint8Array(buffer);
        const hex = [];
        for (let i = 0; i < bytes.length; i++) hex.push(bytes[i].toString(16).padStart(2, '0'));
        return hex.join('');
    }

    function showSuccessMessage(message) {
        removeExistingMessages();
        const successDiv = document.createElement('div');
        successDiv.className = 'alert alert-success alert-dismissible fade show';
        successDiv.innerHTML = `\n            <strong>成功！</strong> ${message}\n            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>\n        `;
        form.parentNode.insertBefore(successDiv, form);
    }

    function showErrorMessage(message) {
        removeExistingMessages();
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-danger alert-dismissible fade show';
        errorDiv.innerHTML = `\n            <strong>错误！</strong> ${message}\n            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>\n        `;
        form.parentNode.insertBefore(errorDiv, form);
        const firstInput = form.querySelector('input[type="text"], input[type="password"]');
        if (firstInput) firstInput.focus();
    }

    function removeExistingMessages() {
        const existingAlerts = document.querySelectorAll('.alert');
        existingAlerts.forEach(alert => alert.remove());
    }
});